#include "httpserver.hpp"

#define WWWROOT "./wwwroot"

std::string RequestStr(const HttpRequest& req)  // 把请求又给序列化了，准备放回到响应的正文里
{
    std::stringstream ss;
    ss << req._method << " " << req._path << " " << req._version << "\r\n";
    for(auto &it : req._params) // 组织的响应正文里带上请求的各种信息，这个是查询字符串
    {
        ss << it.first << ": " << it.second << "\r\n";
    }
    for(auto &it : req._headers)
    {
        ss << it.first << ": " << it.second << "\r\n";
    }
    ss << "\r\n";
    ss << req._body;
    return ss.str();
}

void Hello(const HttpRequest& req, HttpResponse *rsp)
{
    rsp->SetContent(RequestStr(req), "text/plain");     // 文本类型
    rsp->_statu = 200;  // 默认200
    // sleep(20);
}

void Login(const HttpRequest& req, HttpResponse *rsp)
{
    rsp->SetContent(RequestStr(req), "text/plain");     // 文本类型
    rsp->_statu = 200;  // 默认200
}

void PutFile(const HttpRequest& req, HttpResponse *rsp)
{
    // rsp->SetContent(RequestStr(req), "text/plain");     // 文本类型
    // rsp->_statu = 200;  // 默认200

    std::string pathname = WWWROOT + req._path;
    Util::WriteFile(pathname, req._body);
}

void DeleteFile(const HttpRequest& req, HttpResponse *rsp)
{
    rsp->SetContent(RequestStr(req), "text/plain");     // 文本类型
    rsp->_statu = 200;  // 默认200
}

int main()
{
    HttpServer server(8202);
    server.SetThreadCount(3);
    server.SetBaseDir(WWWROOT);
    server.Get("/hello", Hello);
    server.Post("/login", Login);
    server.Put("/123.txt", PutFile);
    server.Delete("/111.txt", DeleteFile);
    server.Listen();

    return 0;
}